import { Entity, Column, ManyToOne, OneToMany, JoinColumn, Index } from 'typeorm';
import { BaseEntity } from '@app/common/entities/base.entity';

@Entity('menus')
@Index(['name'])
@Index(['path'])
export class Menu extends BaseEntity {
  @Column({ type: 'int', nullable: true })
  parentId?: number;

  @Column({ type: 'tinyint', default: 1, comment: '菜单类型: 0=目录, 1=菜单, 2=按钮' })
  type: number;

  @Column({ type: 'varchar', length: 100 })
  title: string;

  @Column({ type: 'varchar', length: 100, nullable: true })
  i18nKey?: string;

  @Column({ type: 'varchar', length: 100})
  name: string;

  @Column({ type: 'varchar', length: 255 })
  path?: string;

  @Column({ type: 'varchar', length: 255, nullable: true })
  component?: string;

  @Column({ type: 'varchar', length: 255, nullable: true })
  permission?: string;

  @Column({ type: 'varchar', length: 100, nullable: true })
  icon?: string;

  @Column({ type: 'varchar', length: 50, default: 'iconify' })
  iconType: string;

  @Column({ type: 'int', default: 0 })
  order: number;

  @Column({ type: 'boolean', default: false })
  isExt: boolean;

  @Column({ type: 'varchar', length: 50, default: '_blank' })
  extOpenMode: string;

  @Column({ type: 'varchar', length: 500, nullable: true })
  href?: string;

  @Column({ type: 'boolean', default: false })
  keepAlive: boolean;

  @Column({ type: 'boolean', default: false })
  hideInMenu: boolean;

  @Column({ type: 'varchar', length: 100, nullable: true })
  activeMenu?: string;

  @Column({ type: 'boolean', default: false })
  multiTab: boolean;

  @Column({ type: 'int', nullable: true })
  fixedIndexInTab?: number;

  @Column({ type: 'tinyint', default: 1, comment: '状态: 0=禁用, 1=启用' })
  status: number;

  // 父菜单关联
  @ManyToOne(() => Menu, menu => menu.children)
  @JoinColumn({ name: 'parentId' })
  parent?: Menu;

  // 子菜单关联
  @OneToMany(() => Menu, menu => menu.parent)
  children?: Menu[];

  // 虚拟属性：获取层级
  get level(): number {
    let level = 1;
    let parent = this.parent;
    while (parent) {
      level++;
      parent = parent.parent;
    }
    return level;
  }

  // 虚拟属性：获取完整路径
  get fullPath(): string {
    if (!this.parent) return this.path || '';
    return `${this.parent.fullPath}/${this.path}`.replace(/\/+/g, '/');
  }

  // 虚拟属性：是否为根菜单
  get isRoot(): boolean {
    return !this.parentId;
  }

  // 虚拟属性：是否有子菜单
  get hasChildren(): boolean {
    return !!this.children && this.children.length > 0;
  }
}
